<?php

class ProjectController extends GeanyController {
    
    // <editor-fold defaultstate="collapsed" desc="STATIC & PRIVATE VARIABLE DECLARATION">
    private $validator;
    const _FUNCTION_ID = 'project';
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="CONSTRUCTOR">
  
    public function __construct(){
        parent::__construct();
        $this->loadDefaultValue();
        $this->loadServices();
        $this->validator = null;
    }
	
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="ACTION-HANDLER">
  
    public function index(){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
        
        $data['Model'] = $this->mService->getList();
        
        return View::make('project/index', $data);
	}

    public function create(){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }

        $project = new Project();
        try {
            if(Input::get('submit')==null) {
                $project->setCreatedDate(date('d-m-y'));
                $project->setCreatedBy($this->userInformation());
                return $this->createInputView($project);
            } else {
                $project = $this->bindData();
                if($this->validateInput(Input::all())==FALSE) return $this->createInputView($project);
                $this->mService->setUserInformation($this->userInformation());
                $newId = $this->mService->insertObject($project);
                if($newId!==null){
                    return Redirect::to('project/detail/'.$newId);
                    //Return Redirect::to('task/create/'.$newprojectId);
                }
                return $this->createInputView($project);
            }
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            return $this->createInputView($project);
        }
    }
    
    public function detail($id=null){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
        
        try {
            $result = $this->mService->getObject($id);
            if($result==null) {
                PageData::addModelError("Project Not Found ");
                Return Redirect::to('project')->with('ModelState',PageData::getModelState());
            }
            $data['Model'] = $result;
            return View::make('project/detail', $data);
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            return Redirect::to('functions');
        }
    }
    
    public function edit($id=null){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
        
        $project = new Project();
        
        try {
            if(Input::get('submit')==null){
                $project = $this->mService->getObject($id);
                return $this->createInputView($project);
            } else{
                $project = $this->bindData();
                if($this->validateInput(Input::all())==FALSE) return $this->createInputView($project);
                $this->mService->setUserInformation($this->userInformation());
                if($this->mService->updateObject($project,$project->getId())==true){
                    Return Redirect::to('project/detail/'.$project->getId());
                }
                return $this->createInputView($project);
            }
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            return $this->createInputView($project);
        }
    }

    
//    public function delete($id=null){
//        if (!$this->isLogin()){ return Redirect::to('login'); }
//        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
//
//        try {
//            $this->mService->deleteObject($id);
//            Return Redirect::to('project');
//        } catch (Exception $exc) {
//            PageData::addModelError($exc->getMessage());
//            Return Redirect::to('project');
//        }
//y    }
    
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="PRIVATE-FUNCTION">
    
    private function loadComboEmployee($show_all = false){
        $arr_data = array();
        
        if ($show_all) $arr_data[''] = 'Pilih Nilai';
        $UserDao = new UserDao();
        $users = $UserDao->getListByGroup('employee');
        foreach ($users as $item){
            $arr_data[$item->getId()] = $item->getName();
        }
        
        $this->data['EmployeeCombo'] = $arr_data;
    }
    
    
    private function loadComboPriority($show_all = false){
        $arr_data = array();
        
        if ($show_all) $arr_data[''] = '';
        $PriorityDao = new PriorityDao();
        $priority = $PriorityDao->getList();
        foreach ($priority as $item){
            $arr_data[$item->getId()] = $item->getName();
        }
        
        $this->data['PriorityCombo'] = $arr_data;
    }
    
    private function createInputView($project=null){
        $this->loadComboEmployee();
        $this->loadComboPriority();
        $this->data['Model'] = $project;
        return View::make('project/input', $this->data);
    }
    
    private function bindData(){
        $data = Input::all();
        $project = New Project();
        $project->setId($data["id"]);
        $project->setName($data["name"]);
        $project->setDescription($data["description"]);
        $project->setStartDate(date("Y/m/d",strtotime($data["startdate"])));
        $project->setDueDate(date("Y/m/d",strtotime($data["duedate"])));
            $user = new User();
            $user->setId($data["createdby"]);
            $user->setIsLoaded(true);
            $project->setCreatedBy($user);
        $project->setCreatedDate(date("Y/m/d",strtotime($data["createdat"])));
        
            $projectAssignments = [];
            $projectAssignmentIds = Input::get('projectProjectAssignment', array());
            for($i=0; $i<count($projectAssignmentIds); $i++) {
                $projectAssignment = new ProjectAssignment();
                $projectAssignment->setId($data["projectProjectAssignmentId"][$i]);
                
                    $projectAssignmentProject = new project();
                    $projectAssignmentProject->setId($project->getId());
                    $projectAssignmentProject->setIsLoaded(true);
                    $projectAssignment->setProject($projectAssignmentProject);
                    
                    $ProjectAssignmentEmployee = new user();
                    $ProjectAssignmentEmployee->setId($data["projectProjectAssignmentUserId"][$i]);
                    $ProjectAssignmentEmployee->setIsLoaded(true);
                    $projectAssignment->setUser($ProjectAssignmentEmployee);
                
                $projectAssignments[] = $projectAssignment;
            }
            
            $project->setProjectAssignment($projectAssignments);
            
            $projectTasks = [];
            $projectTaskIds = Input::get('projectTask', array());
            for($i=0; $i<count($projectTaskIds); $i++) {
                $projectTask = new Task();
                $projectTask->setId($data["projectTaskId"][$i]);
                
                    $projectTaskProject = new project();
                    $projectTaskProject->setId($data["projectTaskProjectId"][$i]);
                    $projectTaskProject->setIsLoaded(true);
                    $projectTask->setProject($projectTaskProject);
                    
                    $projectTaskStatus = new status();
                    $projectTaskStatus->setId($data["projectTaskStatusId"][$i]);
                    $projectTaskStatus->setIsLoaded(true);
                    $projectTask->setStatus($projectTaskStatus);
                
                $projectTask->setName($data["projectTaskName"][$i]);
                $projectTask->setStartDate(date("Y/m/d",strtotime($data["projectTaskStartDate"][$i])));
                $projectTask->setDueDate(date("Y/m/d",strtotime($data["projectTaskDueDate"][$i])));
                
                    $projectTaskPriority = new Priority();
                    $projectTaskPriority->setId($data["projectTaskPriorityId"][$i]);
                    $projectTaskPriority->setIsLoaded(true);
                    $projectTask->setPriority($projectTaskPriority);
                
                $projectTask->setNotes($data["projectTaskNotes"][$i]);
                $projectTask->setIsLoaded(true);
                
                $projectTasks[] = $projectTask;
            }
            
            $project->setTasks($projectTasks);
        
//                echo "<pre>";
//                print_r($data);
//                print_r($project);
//                die();
        return $project;
    }
 
    private function validateInput($data){

        if($data==null) return false;
        $rules = array(
            'name' => 'required',
            'startdate' => 'date|required',
            'duedate' => 'date|required'
        );

        $this->validator = Validator::make($data, $rules);
        if($this->validator->fails()) PageData::assignValidatorToModelState ($this->validator);
        return $this->validator->passes();
    }
    
    private function loadDefaultValue(){
        $this->setFunctionId(self::_FUNCTION_ID);
        $this->page_data['_MODULE_NAME'] = $this->getFunctionName();
    }

    private function loadServices(){
        $this->mService = new ProjectService();
    }
    
    // </editor-fold>
    
}
?>